package com.foreknow.elm.framework;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@WebServlet("/")
public class DispatcherServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out= response.getWriter();
//        处理字符编码
//        获取客户端发送的请求路径(url的部分路径) /controller类名/controller方法名
        String path=request.getServletPath();
//        根据获取到的路径得到类名和方法名
        String className=path.substring(1,path.lastIndexOf("/"));
        String methodName=path.substring(path.lastIndexOf("/")+1);
        try {
//            通过class.forName()方法获取到Controller中类的信息
            Class clazz=Class.forName("com.foreknow.elm.controller."+className);
//            将获取到的类转换为对象（LoginController对象）
            Object controller=clazz.newInstance();
//            获取方法
            Method method=clazz.getMethod(methodName,new Class[]{HttpServletRequest.class});
//            调用方法
            Object result=method.invoke(controller,new Object[]{request});
//            将结果result以json的数据格式响应给客户端浏览器
            ObjectMapper objectMapper=new ObjectMapper();
            out.print(objectMapper.writeValueAsString(result));
        } catch (ClassNotFoundException | NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
